package com.rong.juc_test.juc_base.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer> {

    // 拆分时差值不能超过10
    private static final Integer VALUE = 10;
    private int begin;
    private int end;
    private int result;

    //有参构造
    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    // 拆分和合并过程
    @Override
    protected Integer compute() {
        // 判断相加的两个数是否大于10
        if (end - begin <= VALUE){
            // 相加
            for(int i = begin; i<= end; i++){
                result += i;
            }
        }else {
            // 继续拆分
            int mid =  (begin + end) / 2;
            MyTask task1 = new MyTask(begin, mid);
            MyTask task2 = new MyTask(mid + 1, end);
            // 拆分
            task1.fork();
            task2.fork();
            // 合并
            result = task1.join() + task2.join();
        }
        return result;
    }
}
public class ForkJoinDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(0,100);
        // 创建分支合并池对象
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
        // 获取合并后的结果
        Integer result = forkJoinTask.get();
        System.out.println(result);

        // 关闭池对象
        forkJoinPool.shutdown();
    }
}
